<template>
  <div class="register-page">
    <div class="register-container">
      <div class="register-box">
        <h2>注册</h2>
        <form @submit.prevent="handleRegister">
          <div class="form-group">
            <label for="userName">用户名 <span class="required">*</span></label>
            <input 
              type="text" 
              id="userName" 
              v-model="registerForm.userName" 
              :class="{ 'error': errors.userName }"
              placeholder="请输入用户名" 
            />
            <span class="error-message" v-if="errors.userName">{{ errors.userName }}</span>
          </div>
          
          <div class="form-group">
            <label for="nickName">昵称</label>
            <input 
              type="text" 
              id="nickName" 
              v-model="registerForm.nickName" 
              :class="{ 'error': errors.nickName }"
              placeholder="请输入昵称" 
            />
            <span class="error-message" v-if="errors.nickName">{{ errors.nickName }}</span>
          </div>
          
          <div class="form-group">
            <label for="email">邮箱</label>
            <input 
              type="email" 
              id="email" 
              v-model="registerForm.email" 
              :class="{ 'error': errors.email }"
              placeholder="请输入邮箱" 
            />
            <span class="error-message" v-if="errors.email">{{ errors.email }}</span>
          </div>
          
          <div class="form-group">
            <label for="phone">手机号</label>
            <input 
              type="tel" 
              id="phone" 
              v-model="registerForm.phone" 
              :class="{ 'error': errors.phone }"
              placeholder="请输入手机号" 
            />
            <span class="error-message" v-if="errors.phone">{{ errors.phone }}</span>
          </div>
          
          <div class="form-group">
            <label for="password">密码 <span class="required">*</span></label>
            <input 
              type="password" 
              id="password" 
              v-model="registerForm.password" 
              :class="{ 'error': errors.password }"
              placeholder="请输入密码" 
            />
            <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
          </div>
          
          <div class="form-group">
            <label for="confirmPassword">确认密码 <span class="required">*</span></label>
            <input 
              type="password" 
              id="confirmPassword" 
              v-model="registerForm.confirmPassword" 
              :class="{ 'error': errors.confirmPassword }"
              placeholder="请再次输入密码" 
            />
            <span class="error-message" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</span>
          </div>
          
          <div class="form-group">
            <label>性别</label>
            <div class="radio-group">
              <label class="radio-label">
                <input type="radio" v-model="registerForm.sex" :value="1"> 男
              </label>
              <label class="radio-label">
                <input type="radio" v-model="registerForm.sex" :value="2"> 女
              </label>
              <label class="radio-label">
                <input type="radio" v-model="registerForm.sex" :value="0"> 保密
              </label>
            </div>
          </div>
          
          <div class="form-group">
            <label for="introduce">个人介绍</label>
            <textarea 
              id="introduce" 
              v-model="registerForm.introduce" 
              :class="{ 'error': errors.introduce }"
              placeholder="请输入个人介绍" 
              rows="3"
            ></textarea>
            <span class="error-message" v-if="errors.introduce">{{ errors.introduce }}</span>
          </div>
          
          <div class="form-group checkbox">
            <label class="checkbox-label">
              <input type="checkbox" v-model="registerForm.agreement">
              我已阅读并同意 <a href="#" @click.prevent="showTermsDialog">《用户协议》</a> 和 <a href="#" @click.prevent="showPrivacyDialog">《隐私政策》</a>
            </label>
            <span class="error-message" v-if="errors.agreement">{{ errors.agreement }}</span>
          </div>
          
          <!-- 添加注册错误消息显示区域 -->
          <div class="error-alert" v-if="registerError">
            {{ registerError }}
          </div>
          
          <button type="submit" :disabled="loading">
            {{ loading ? '注册中...' : '注册' }}
          </button>
        </form>
        
        <div class="footer">
          <router-link to="/login">已有账号？立即登录</router-link>
        </div>
      </div>
    </div>
    
    <!-- 用户协议对话框 -->
    <div class="dialog-overlay" v-if="showTerms" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>用户协议</h3>
          <button class="close-btn" @click="closeDialog">&times;</button>
        </div>
        <div class="dialog-body">
          <h4>CarbonSpark用户协议</h4>
          <p>欢迎使用CarbonSpark服务！</p>
          <p>本协议是您与CarbonSpark平台之间关于使用CarbonSpark服务所订立的契约。请您仔细阅读本协议，如果您不同意本协议中的任何条款，您应当停止注册/使用流程。当您完成注册并开始使用CarbonSpark服务时，即表示您已充分阅读、理解并接受本协议的全部内容。</p>
          
          <h5>1. 服务内容</h5>
          <p>CarbonSpark是一个编程挑战平台，旨在为用户提供编程学习、实践和竞赛的环境。</p>
          
          <h5>2. 账号注册与安全</h5>
          <p>2.1 您在注册时应当提供真实、准确、完整的个人资料，并在资料发生变更时及时更新。</p>
          <p>2.2 您应当妥善保管账号和密码，因账号或密码保管不善导致的损失由您自行承担。</p>
          
          <h5>3. 用户行为规范</h5>
          <p>3.1 您在使用CarbonSpark服务时，必须遵守中华人民共和国相关法律法规。</p>
          <p>3.2 未经CarbonSpark许可，您不得利用本平台进行任何商业行为。</p>
          
          <h5>4. 知识产权</h5>
          <p>4.1 CarbonSpark平台所有内容，包括但不限于文字、图片、音频、视频、软件、程序、数据及平台设计所产生的知识产权，均属于CarbonSpark所有。</p>
          <p>4.2 未经CarbonSpark许可，任何人不得擅自使用、修改、复制、传播、发行平台内容。</p>
          
          <h5>5. 协议修改</h5>
          <p>CarbonSpark有权在必要时修改本协议条款，并在平台上公示。您可以在平台查阅最新版协议条款。</p>
        </div>
        <div class="dialog-footer">
          <button @click="closeDialog">关闭</button>
        </div>
      </div>
    </div>
    
    <!-- 隐私政策对话框 -->
    <div class="dialog-overlay" v-if="showPrivacy" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>隐私政策</h3>
          <button class="close-btn" @click="closeDialog">&times;</button>
        </div>
        <div class="dialog-body">
          <h4>CarbonSpark隐私政策</h4>
          <p>本隐私政策介绍了CarbonSpark如何收集、使用、储存和分享您的个人信息。请您仔细阅读本政策，以便了解我们对您个人信息的处理方式。</p>
          
          <h5>1. 我们收集的信息</h5>
          <p>1.1 您提供的信息：包括但不限于注册信息（用户名、密码）、个人资料（昵称、邮箱、手机号、性别、个人介绍）等。</p>
          <p>1.2 我们自动收集的信息：包括但不限于IP地址、浏览器类型、访问时间、访问页面等。</p>
          
          <h5>2. 信息使用</h5>
          <p>2.1 提供服务：我们使用收集的信息来提供、维护和改进CarbonSpark服务。</p>
          <p>2.2 安全保障：我们可能使用您的信息来保障平台和用户的安全。</p>
          
          <h5>3. 信息共享</h5>
          <p>除非获得您的明确同意，或法律法规要求，我们不会与第三方分享您的个人信息。</p>
          
          <h5>4. 信息存储与安全</h5>
          <p>我们采取各种安全措施来保护您的个人信息不被未经授权的访问、使用或泄露。</p>
          
          <h5>5. 您的权利</h5>
          <p>您有权访问、修改、删除您的个人信息，以及撤回您的同意。</p>
        </div>
        <div class="dialog-footer">
          <button @click="closeDialog">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { register } from '@/api/auth'

export default {
  name: 'RegisterPage',
  data() {
    return {
      registerForm: {
        userName: '',
        nickName: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        sex: 0,
        introduce: '',
        agreement: false
      },
      errors: {},
      loading: false,
      registerError: '',
      showTerms: false,
      showPrivacy: false
    }
  },
  methods: {
    validateForm() {
      this.errors = {}
      let isValid = true
      
      // 用户名验证 (必填)
      if (!this.registerForm.userName) {
        this.errors.userName = '请输入用户名'
        isValid = false
      } else if (this.registerForm.userName.length < 3 || this.registerForm.userName.length > 32) {
        this.errors.userName = '用户名长度应在3-32个字符之间'
        isValid = false
      } else if (!/^[a-zA-Z0-9_]+$/.test(this.registerForm.userName)) {
        this.errors.userName = '用户名只能包含字母、数字和下划线'
        isValid = false
      }
      
      // 昵称验证 (可选)
      if (this.registerForm.nickName) {
        if (this.registerForm.nickName.length < 2 || this.registerForm.nickName.length > 32) {
          this.errors.nickName = '昵称长度应在2-32个字符之间'
          isValid = false
        }
      }
      
      // 邮箱验证 (可选)
      if (this.registerForm.email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailRegex.test(this.registerForm.email)) {
          this.errors.email = '请输入有效的邮箱地址'
          isValid = false
        } else if (this.registerForm.email.length > 32) {
          this.errors.email = '邮箱长度不能超过32个字符'
          isValid = false
        }
      }
      
      // 手机号验证 (可选)
      if (this.registerForm.phone) {
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(this.registerForm.phone)) {
          this.errors.phone = '请输入有效的手机号码'
          isValid = false
        } else if (this.registerForm.phone.length > 32) {
          this.errors.phone = '手机号长度不能超过32个字符'
          isValid = false
        }
      }
      
      // 密码验证 (必填)
      if (!this.registerForm.password) {
        this.errors.password = '请输入密码'
        isValid = false
      } else if (this.registerForm.password.length < 6 || this.registerForm.password.length > 64) {
        this.errors.password = '密码长度应在6-64个字符之间'
        isValid = false
      } else if (!/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,64}$/.test(this.registerForm.password)) {
        this.errors.password = '密码必须包含英文字母和数字'
        isValid = false
      }
      
      // 确认密码验证
      if (!this.registerForm.confirmPassword) {
        this.errors.confirmPassword = '请确认密码'
        isValid = false
      } else if (this.registerForm.confirmPassword !== this.registerForm.password) {
        this.errors.confirmPassword = '两次输入的密码不一致'
        isValid = false
      }
      
      // 个人介绍验证 (可选)
      if (this.registerForm.introduce && this.registerForm.introduce.length > 255) {
        this.errors.introduce = '个人介绍不能超过255个字符'
        isValid = false
      }
      
      // 用户协议验证
      if (!this.registerForm.agreement) {
        this.errors.agreement = '请阅读并同意用户协议和隐私政策'
        isValid = false
      }
      
      return isValid
    },
    async handleRegister() {
      if (!this.validateForm()) {
        return
      }

      this.loading = true
      try {
        // 准备注册数据
        const userData = {
          userName: this.registerForm.userName,
          nickName: this.registerForm.nickName || null,
          email: this.registerForm.email || null,
          phone: this.registerForm.phone || null,
          password: this.registerForm.password,
          sex: this.registerForm.sex,
          introduce: this.registerForm.introduce || null
        }

        // 调用注册 API
        const response = await register(userData)
        
        // 处理响应
        if (response.success) {
          // 注册成功，跳转到登录页
          this.$router.push('/login')
        } else {
          // 注册失败，显示错误信息
          this.registerError = response.message || '注册失败，请稍后重试'
        }
      } catch (error) {
        console.error('注册错误:', error)
        this.registerError = error.message || '注册失败，请稍后重试'
      } finally {
        this.loading = false
      }
    },
    // 添加显示用户协议和隐私政策的方法
    showTermsDialog() {
      this.showTerms = true;
    },
    showPrivacyDialog() {
      this.showPrivacy = true;
    },
    closeDialog() {
      this.showTerms = false;
      this.showPrivacy = false;
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.register-box {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 500px;
}

h2 {
  color: #4CAF50;
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
}

input[type="text"],
input[type="email"],
input[type="tel"],
input[type="password"],
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  text-align: left;
}

input[type="text"]:focus,
input[type="email"]:focus,
input[type="tel"]:focus,
input[type="password"]:focus,
textarea:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-label {
  display: flex;
  align-items: center;
  margin: 0;
  cursor: pointer;
}

.radio-label input[type="radio"] {
  margin-right: 8px;
}

textarea {
  resize: vertical;
  min-height: 100px;
}

.agreement {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.agreement label {
  display: flex;
  align-items: flex-start;
  margin: 0;
  cursor: pointer;
}

.agreement input[type="checkbox"] {
  margin-right: 8px;
  margin-top: 3px;
}

.agreement a {
  color: #4CAF50;
  text-decoration: none;
}

.agreement a:hover {
  text-decoration: underline;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover:not(:disabled) {
  background-color: #3d8b40;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.footer {
  margin-top: 20px;
  text-align: center;
}

.footer a {
  color: #4CAF50;
  text-decoration: none;
}

.footer a:hover {
  text-decoration: underline;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
  text-align: left;
  display: block;
}

input.error,
textarea.error {
  border-color: #ff4d4f;
  text-align: left;
}

input.error:focus,
textarea.error:focus {
  border-color: #ff4d4f;
  box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
}

.error-alert {
  background-color: #ffebee;
  color: #d32f2f;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 14px;
  text-align: center;
  border-left: 4px solid #d32f2f;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  color: #4CAF50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
  cursor: pointer;
}

.dialog-body {
  padding: 20px;
  overflow-y: auto;
  max-height: calc(80vh - 130px);
}

.dialog-body h4 {
  margin-top: 0;
  color: #333;
}

.dialog-body h5 {
  margin-top: 16px;
  margin-bottom: 8px;
  color: #555;
}

.dialog-body p {
  margin-bottom: 12px;
  line-height: 1.5;
  color: #666;
}

.dialog-footer {
  padding: 16px 20px;
  border-top: 1px solid #eee;
  text-align: right;
}

.dialog-footer button {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  width: auto;
}

.dialog-footer button:hover {
  background-color: #3d8b40;
}
</style> 